/**
 * 账户登陆界面
 * @author William
 * 2012-5-10
 */
package com.ytu.clouddisk.face;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

import com.ytu.clouddisk.clientlogin.LoginUtil;
import com.ytu.clouddisk.kanbox.KanBoxControl;

import android.widget.Toast;

public class CloudDiskLoginActivity extends Activity {

	private ExpandableListView expandableListView;
	private Button btnOK;
	private Button btnExit;
	private static ProgressDialog dlg_refresh;
	private OnClickListener listenerBtn;
	private SharedPreferences sp;
	private ExListAdapter adapter;
	private List<Map<String, Object>> parentList;
	private ArrayList<ArrayList<HashMap<String, Object>>> allchildList;

	// 表示是否登陆
	private boolean isGoogleLogin = false;
	private boolean isVDiskLogin = false;
	private boolean isKanBoxLogin = false;
	private boolean isKuaiPanLogin = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}

	/**
	 * 清理账户配置文件
	 * 
	 * @param bg
	 *            表示是否记住google账户，若是为真
	 * @param bv
	 *            表示是否记住VDISK账户，若是为真
	 */
	protected void clearCfg(boolean bg, boolean bv) {
		if (sp == null)
			sp = getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE);
		if (!bg && !bv)
			sp.edit().clear().commit();
		else {
			sp.edit().remove(Varibles.KANBOX_ACCESS_TOKEN).commit();
			sp.edit().remove(Varibles.GOOGLE_TOKEN).commit();
			sp.edit().remove(Varibles.VDISK_TOKEN).commit();
			if (!bg) { // 如果没记住google账户
				sp.edit().remove(Varibles.GOOGLE_ACCOUNT + "User").commit();
				sp.edit().remove(Varibles.GOOGLE_ACCOUNT + "Psd").commit();
			}
			if (!bv) { // 如果没记住vdisk账户
				sp.edit().remove(Varibles.VDISK_ACCOUNT + "User").commit();
				sp.edit().remove(Varibles.VDISK_ACCOUNT + "Psd").commit();
			}
		}
	}

	/**
	 * 检测账户是否配置
	 * 
	 * @param user
	 * @param psd
	 * @return
	 */
	private boolean checkAccount(String user, String psd) {
		return getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE).contains(user) && getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE).contains(psd);
	}

	/**
	 * 初始化
	 */
	protected void init() {
		expandableListView = (ExpandableListView) findViewById(R.id.expandlistview);
		btnOK = (Button) findViewById(R.id.btn_ok);
		btnExit = (Button) findViewById(R.id.btn_exit);

		listenerBtn = new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v.equals(btnOK)) {
					Intent intent = new Intent(CloudDiskLoginActivity.this,
							BrowserActivity.class);
					startActivity(intent);
				} else if (v.equals(btnExit)) {
					clearCfg(false, false);
					finish();
				}
			}

		};

		btnOK.setOnClickListener(listenerBtn);
		btnExit.setOnClickListener(listenerBtn);
		sp = getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE);
		parentList = new ArrayList<Map<String, Object>>();
		allchildList = new ArrayList<ArrayList<HashMap<String, Object>>>();
		// 添加第一父列
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		map1.put("parent", "账号登陆");
		parentList.add(map1);

		ArrayList<HashMap<String, Object>> childlist1 = new ArrayList<HashMap<String, Object>>();
		// 第一父列的第一子列
		HashMap<String, Object> childmap1 = new HashMap<String, Object>();
		childmap1.put("child", "Docs");
		childlist1.add(childmap1);
		// 第一父列的第二子列
		HashMap<String, Object> childmap2 = new HashMap<String, Object>();
		childmap2.put("child", "微盘");
		childlist1.add(childmap2);

		allchildList.add(childlist1);

		// 添加第二父列
		HashMap<String, Object> map2 = new HashMap<String, Object>();
		map2.put("parent", "网页登陆");
		parentList.add(map2);

		ArrayList<HashMap<String, Object>> childlist2 = new ArrayList<HashMap<String, Object>>();
		// 第二父列的第一子列
		HashMap<String, Object> childmap3 = new HashMap<String, Object>();
		childmap3.put("child", "酷盘");
		childlist2.add(childmap3);
		// 第二父列的第二子列
		HashMap<String, Object> childmap4 = new HashMap<String, Object>();
		childmap4.put("child", "快盘");
		childlist2.add(childmap4);
		allchildList.add(childlist2);

		adapter = new ExListAdapter(this);
		expandableListView.setAdapter(adapter);

		expandableListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
//				Toast.makeText(
//						CloudDiskLoginActivity.this,
//						String.valueOf(groupPosition) + "  "
//								+ String.valueOf(childPosition),
//						Toast.LENGTH_SHORT).show();
				setTitle("ddddddd");
				return false;
			}

		});
	}
	
	

	/**
	 * 内部适配器类
	 */
	class ExListAdapter extends BaseExpandableListAdapter {

		Context context;
		LayoutInflater mlayoutInflater;

		ExListAdapter(Context context) {
			this.context = context;
			mlayoutInflater = LayoutInflater.from(context);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {

			return allchildList.get(groupPosition).get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {

			return childPosition;
		}

		// 子列
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			convertView = mlayoutInflater.inflate(R.layout.childview, null);

//			final int parentPos = groupPosition;
//			final int childPos = childPosition;
			// TextView的处理
			TextView tv = (TextView) convertView
					.findViewById(R.id.service_name);
			tv.setText(allchildList.get(groupPosition).get(childPosition)
					.get("child").toString());

			// 登陆按钮
			Button btnLogin = (Button) convertView.findViewById(R.id.btn_login);
            int m = parent.getChildCount();
            Object tmp = allchildList.get(groupPosition).get(childPosition-1);
            
	     	btnLogin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (.equals("Docs")) { 
						// 多线程
						if (!checkAccount(Varibles.GOOGLE_ACCOUNT + "User",         //包含就返回真
								Varibles.GOOGLE_ACCOUNT + "Psd")) {
							Toast.makeText(CloudDiskLoginActivity.this,
									"请先配置账户", Toast.LENGTH_SHORT).show();
							return;
						}
						dlg_refresh = ProgressDialog.show(
								CloudDiskLoginActivity.this,
								"Please waiting...", "Docs登录中...", true);
						new LoginThread(Varibles.GOOGLEDOCS).start();
					} else if (((Button)v).getText().toString().equals("微盘")) {
						if (!checkAccount(Varibles.VDISK_ACCOUNT + "User",      //包含就返回真
								Varibles.VDISK_ACCOUNT + "Psd")) {
							Toast.makeText(CloudDiskLoginActivity.this,
									"请先配置账户", Toast.LENGTH_SHORT).show();
							return;
						}
						dlg_refresh = ProgressDialog.show(
								CloudDiskLoginActivity.this,
								"Please waiting...", "VDisk登录中...", true);
						new LoginThread(Varibles.VDISK).start();

					} else if (((Button)v).getText().toString().equals("酷盘")) {
						KanBoxControl.getInstance(CloudDiskLoginActivity.this)
								.getOauth(); // 启动网页页面
					} else if (((Button)v).getText().toString().equals("快盘")) {

					}
				}
				
			});

			// 修改按钮的处理 检测所有配置账户
			Button btnModifySetting = (Button) convertView
					.findViewById(R.id.btn_modify_settings);

			if (allchildList.get(groupPosition).get(childPosition).get("child")
					.toString().equals("Docs")) {
				btnModifySetting.setVisibility(View.VISIBLE);
				if (checkAccount(Varibles.GOOGLE_ACCOUNT + "User",
						Varibles.GOOGLE_ACCOUNT + "Psd")) {
					btnModifySetting.setText("修改");
					btnLogin.setText("登录");
				} else {
					btnModifySetting.setText("设置"); // 如果不存在
				}
			} else if (allchildList.get(groupPosition).get(childPosition).get("child")
					.toString().equals("微盘")) {
				btnModifySetting.setVisibility(View.VISIBLE);
				if (checkAccount(Varibles.VDISK_ACCOUNT + "User",
						Varibles.VDISK_ACCOUNT + "Psd")) {
					btnModifySetting.setText("修改");
					btnLogin.setText("登录");
				} else {
					btnModifySetting.setText("设置");
				}
			} else {
				btnLogin.setText("登录");
			}
			// 单击修改按钮
	/*		btnModifySetting.setOnClickListener(new Button.OnClickListener() {

				@Override
				public void onClick(View v) {
					if (allchildList.get(groupPosition).get(childPos).get("child")
							.toString().equals("Docs")) {
						Intent intent = new Intent(CloudDiskLoginActivity.this,
								AccountConfigActivity.class);
						intent.putExtra("keyCode", Varibles.GOOGLE_REQUEST_CODE);
						startActivityForResult(intent, Varibles.REQUEST_CODE); // 启动设置页面
					} else if (allchildList.get(groupPosition).get(childPos)
							.get("child").toString().equals("微盘")) {
						Intent intent = new Intent(CloudDiskLoginActivity.this,
								AccountConfigActivity.class);
						intent.putExtra("keyCode", Varibles.VDISK_REQUEST_CODE);
						startActivityForResult(intent, Varibles.REQUEST_CODE); // 启动设置页面
					}
				}
			});*/
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return allchildList.get(groupPosition).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return allchildList.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return allchildList.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		// 父列
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			convertView = mlayoutInflater.inflate(R.layout.parentview, null);
			TextView textParent = (TextView) convertView
					.findViewById(R.id.tv_parentview);
			textParent.setText(parentList.get(groupPosition).get("parent")
					.toString());
			return convertView;
		}

		@Override
		public boolean hasStableIds() {

			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
		
	}

	/**
	 * 检索线程
	 * 
	 * @author William
	 * 
	 */
	class LoginThread extends Thread {
		int flag;

		public LoginThread(int m) {
			flag = m;
		}

		public void run() {
			try {
				switch (flag) {
				case Varibles.GOOGLEDOCS:
					// 获取google token
					isGoogleLogin = LoginUtil.GoogleLogin(
							CloudDiskLoginActivity.this, sp.getString(
									Varibles.GOOGLE_ACCOUNT + "User", null), sp
									.getString(Varibles.GOOGLE_ACCOUNT + "Psd",
											null));
					break;
				case Varibles.VDISK:
					isVDiskLogin = LoginUtil
							.VDiskLogin(CloudDiskLoginActivity.this, sp
									.getString(Varibles.VDISK_ACCOUNT + "User",
											null), sp.getString(
									Varibles.VDISK_ACCOUNT + "Psd", null));
					break;
				default:
					break;
				}

			} catch (Exception e) {
				Toast.makeText(CloudDiskLoginActivity.this, "程序错误",
						Toast.LENGTH_SHORT).show();
				finish();
			} finally {
				docsHandler.sendEmptyMessage(0);
			}
		}
	}

	private Handler docsHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dlg_refresh.dismiss();
			if (isGoogleLogin) {
				Toast.makeText(CloudDiskLoginActivity.this, "登陆成功",
						Toast.LENGTH_SHORT).show();
				return;
			} else if(isVDiskLogin){
				Toast.makeText(CloudDiskLoginActivity.this, "登陆成功",
						Toast.LENGTH_SHORT).show();
				return;
			}else{
				Toast.makeText(CloudDiskLoginActivity.this, "登陆失败",
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent in) {
		if (requestCode == Varibles.REQUEST_CODE) {
			if (resultCode == Varibles.GOOGLE_REQUEST_CODE) {
				Bundle bundle = in.getExtras();
				if (bundle != null) {
					if (bundle.getBoolean("result")) {
						Toast.makeText(CloudDiskLoginActivity.this, "设置成功",
								Toast.LENGTH_SHORT).show();
						return;
					} else{
						Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
								Toast.LENGTH_SHORT).show();
						return;
					}
				} else {
					Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
							Toast.LENGTH_SHORT).show();
					return;
				}

			} else if (resultCode == Varibles.VDISK_REQUEST_CODE) {
				Bundle bundle = in.getExtras();
				if (bundle != null) {
					if (bundle.getBoolean("result")){
						Toast.makeText(CloudDiskLoginActivity.this, "设置成功",
								Toast.LENGTH_SHORT).show();
					  return;
					}else{
						Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
								Toast.LENGTH_SHORT).show();
						return;
					}
				} else {
					Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
							Toast.LENGTH_SHORT).show();
					return;
				}
			} else {
				Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
						Toast.LENGTH_SHORT).show();
				return;
			}
		} else {
			Toast.makeText(CloudDiskLoginActivity.this, "设置失败",
					Toast.LENGTH_SHORT).show();
			return;
		}
	}
}